package logic

import (
	"core/common"
	"core/logic/logicredis"
	"errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type UserInfo struct {
	player   *Player
	nickName string
	dirty    bson.M
	table    string
}

func newUserInfo(player *Player) *UserInfo {
	userInfo := &UserInfo{
		player: player,
		dirty:  bson.M{},
	}
	userInfo.loadFromDB()
	return userInfo
}

func (user *UserInfo) loadFromDB() {
	u := &common.UserInfo{}
	user.table = u.C()
	primKey := bson.M{common.PRIMARYKEY: user.player.playerId}
	err := logicMongo.FindOne(u.C(), primKey, nil, u)
	if errors.Is(err, mongo.ErrNoDocuments) {
		return
	}
	user.nickName = u.NickName
}

func (user *UserInfo) saveDB() {
	if len(user.dirty) == 0 {
		return
	}
	primKey := bson.M{common.PRIMARYKEY: user.player.playerId}
	logicMongo.Upsert(user.table, primKey, bson.M{"$set": user.dirty})
	user.dirty = bson.M{}
}

func (user *UserInfo) setNickName(nickName string) {
	user.nickName = nickName
	logicredis.CacheRedis().Set(common.MakeNickNameKey(nickName), user.player.playerId, 0)
	user.dirty["nickName"] = user.nickName
}
